package com.example.service.impl;

import com.example.mapper.UserAreaMapper;
import com.example.mapper.UserMapper;
import com.example.pojo.AreaLevel;
import com.example.pojo.Poi;
import com.example.pojo.User;
import com.example.pojo.UserArea;
import com.example.service.UserAreaService;
import com.example.utils.ExcelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class UserAreaServiceImpl implements UserAreaService {

    @Autowired
    private UserAreaMapper userAreaMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public String updateUniversityBookstore(String poiPath, String areaPath) {
        List<Poi> poiList = ExcelUtils.readExcel(poiPath, Poi.class);
        List<AreaLevel> areaLevelList = ExcelUtils.readExcel(areaPath, AreaLevel.class);
        if(poiList==null||areaLevelList==null){
            return "文件不存在";
        }
        List<UserArea> userAreaList=new ArrayList<>();
        List<User> userList=new ArrayList<>();
        int countUserArea=0;
        int countUser=0;
        try {
            for (Poi poi : poiList) {
                if(poi.getUserId()==null||poi.getUserId()==-3){
                    continue;
                }
                for (AreaLevel areaLevel : areaLevelList) {
                    if(!poi.getVillageId().equals(areaLevel.getVillageId())){
                        continue;
                    }
                    UserArea userArea=new UserArea();
                    userArea.setUserId(Long.valueOf(poi.getUserId()));
                    userArea.setProvinceId(Long.valueOf(areaLevel.getProvinceId()));
                    userArea.setCityId(Long.valueOf(areaLevel.getCityId()));
                    userArea.setAreaId(Long.valueOf(areaLevel.getUniversityId()));
                    userArea.setVillageId(Long.valueOf(areaLevel.getVillageId()));
                    userAreaList.add(userArea);

                    User user=new User();
                    user.setUserId(Long.valueOf(poi.getUserId()));
                    user.setLocation(areaLevel.getVillage());
                    userList.add(user);
                    break;
                }
                if(userAreaList.size()%1000==0){
                    countUserArea+=userAreaMapper.batchUpdateByUserId(userAreaList);
                    countUser+=userMapper.batchUpdateByUserId(userList);
                    userAreaList.clear();
                    userList.clear();
                }
            }
            if(userAreaList.size()>0){
                countUserArea+=userAreaMapper.batchUpdateByUserId(userAreaList);
                countUser+=userMapper.batchUpdateByUserId(userList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "成功（更新用户地址："+countUserArea+"条，更新用户："+countUser+"条）";
    }
}
